import axios, { type AxiosRequestConfig } from 'axios';
import { type IResponse } from '../types/index';

const serve = axios.create({
  baseURL: '',
});

serve.interceptors.request.use(
  (config) => {
    if (config.method?.toUpperCase() == 'GET') {
      config.params = config.data;
    }

    // token
    const token = localStorage.getItem('token');
    config.headers.Authorization = token;

    return config;
  },
  (err) => {
    console.log(err);
    return Promise.reject(err);
  },
);

serve.interceptors.response.use(
  ({ data }) => {
    const res = data as IResponse;
    if (res.code == 200) {
      return Promise.resolve(res.data);
    }
    return Promise.reject(res.msg);
  },
  (err) => {
    console.log(err);
    return Promise.reject(err);
  },
);

export const http = <T>(config: AxiosRequestConfig) => {
  return serve.request<any, T, any>(config);
};
